//
//  SearchViewController.m
//  vietnameseSlang
//
//  Created by Jason Bargent on 22/09/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import "MyConstants.h"
#import "ASIHTTPRequest.h"
#import "JMUtilities.h"
#import "SearchViewController.h"
#import "JSON.h"


@implementation SearchViewController

@synthesize words;

@synthesize loadingView;

@synthesize svos;
@synthesize isTheViewActive;
@synthesize keywordTextField;
@synthesize searchButton;
@synthesize tableView;

- (void)dealloc {
    
    [words release];
    
	[keywordTextField release];
	[searchButton release];
    [tableView release];
	[super dealloc];
}

-(id)init{
    self = [super init];	
	NSLog(@"Initializing SEARCH controller");
    return self;
}

- (id)initWithTabBar
{
    self = [super init];	
	
	self.navigationItem.title = NSLocalizedString(@"Back",nil);
	self.title = NSLocalizedString(@"Search",nil);
	
	
	self.tabBarItem.image = [UIImage imageNamed:@"tabbar_search.png"];
	self.tabBarItem.title =  NSLocalizedString(@"Search",nil);
    
    return self;
}


- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle


// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
    [super loadView];
	NSLog(@"Loading the view");
	CGRect frame = self.view.bounds;
	
	tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)
											 style:UITableViewStyleGrouped];
	
    tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    tableView.delegate = self;
    tableView.dataSource = self;
	tableView.scrollEnabled = YES;
	[self.tableView setAllowsSelection:YES];
    [self.view addSubview:self.tableView];
    
	// Load the components
	keywordTextField = [[UITextField alloc] init];
	keywordTextField.backgroundColor = [UIColor whiteColor];
	keywordTextField.textColor = [UIColor darkGrayColor];
	keywordTextField.placeholder = @"<Enter keyword>";
	keywordTextField.keyboardType = UIKeyboardTypeDefault;	// use the default type input method (entire keyboard)
	keywordTextField.returnKeyType = UIReturnKeyDone;
	keywordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;	// has a clear 'x' button to the right
	keywordTextField.delegate = self;
	[keywordTextField addTarget:self action:@selector(textFieldActive:) forControlEvents:UIControlEventEditingDidBegin];
	
	searchButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
	searchButton.frame = CGRectMake(0, 0, FORM_BUTTON_WIDTH, FORM_BUTTON_HEIGHT);
	searchButton.backgroundColor = [UIColor clearColor];
	[searchButton setTitle:NSLocalizedString(@"Search",nil) forState:UIControlStateNormal];
	[searchButton addTarget:self action:@selector(searchButtonClicked) forControlEvents:UIControlEventTouchUpInside];
	
	
	UIBarButtonItem *temporaryBarButtonItem = [[UIBarButtonItem alloc] init];
	temporaryBarButtonItem.title = NSLocalizedString(@"Back",nil);
	self.navigationItem.backBarButtonItem = temporaryBarButtonItem;
	[temporaryBarButtonItem release];
	
	[self reset];
}


/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
}
*/

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void) reset {
	keywordTextField.text = @"";
	
}


//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    return 1;
//}

#pragma mark -
#pragma mark Table View Data Source Methods

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return 2;
	
}

- (CGFloat)tableView:(UITableView *)tView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	return 42;
	
}

- (UITableViewCell *)tableView:(UITableView *)tView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	//UITableViewCell *cell = nil;
	
    NSLog(@"Creating one cell");
    
//    static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
//                             SimpleTableIdentifier];
//    if (cell == nil) {
//        cell = [[[UITableViewCell alloc]
//                 initWithStyle:UITableViewCellStyleDefault
//                 reuseIdentifier:SimpleTableIdentifier] autorelease];
//    }
//    cell.textLabel.text = @"Hello World";
//    return cell;
    
    UITableViewCell *cell = nil;
	
	
	if (indexPath.section == 0)  {
		if (indexPath.row == 0) {
			static NSString *kCellTextField_ID1 = @"InputCell_ID";
			cell = [tView dequeueReusableCellWithIdentifier:kCellTextField_ID1];
			
			// a new cell needs to be created
			if (cell == nil) {
				cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1
											   reuseIdentifier:kCellTextField_ID1] autorelease];
				cell.selectionStyle = UITableViewCellSelectionStyleNone;
				
			}
			
			//cell.textLabel.textColor = [UIColor whiteColor];
			//cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
			//cell.detailTextLabel.textColor = [UIColor yellowColor];
			cell.textLabel.text = NSLocalizedString(@"Keyword",nil);//;
			cell.textLabel.font = [UIFont systemFontOfSize:UI_FONT_SIZE_16];						
			
			[self.keywordTextField setFrame:CGRectMake(80, 
													   12, 
													   210, 
													   20)];		
			[self.keywordTextField setFont:[UIFont systemFontOfSize:UI_FONT_SIZE_16]];
			[cell.contentView addSubview:self.keywordTextField];	
			
			
		}
		else if (indexPath.row == 1) {
			
			static NSString *kCellTextField_ID6 = @"ButtonCell_ID";
            cell = [tView dequeueReusableCellWithIdentifier:kCellTextField_ID6];
            if (cell == nil) {
                cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1
                                               reuseIdentifier:kCellTextField_ID6] autorelease];
                [self.searchButton setFrame:CGRectMake(FORM_CELL_PADDING_LARGE/2, 
                                                       FORM_CELL_PADDING_LARGE/2, 
                                                       searchButton.frame.size.width, 
                                                       searchButton.frame.size.height)];
                
                cell.backgroundView = [[UIView alloc] init];
                [cell.contentView addSubview:searchButton];
                
            }
			
		}
		
		
		
	}
	else if (indexPath.section == 1) {
				
	}
	else if(indexPath.section == 2){
		
		
		
	}
	
	
    return cell;
	
}

- (void) tableView:(UITableView *)tView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	
}

#pragma mark -
#pragma mark Button Methods

- (void) searchButtonClicked {
	
	NSLog(@"Clicking the search button");
    [self sendRequest];
	
}

#pragma mark -
#pragma mark UI Interaction

- (void) moveDown:(id)sender
{
	[tableView setContentOffset:svos animated:YES]; 
	
	NSLog(@"move down, set content offset:%f",tableView.contentOffset.y);
	
	self.isTheViewActive = NO;
	
	
}

- (void) moveUp:(id)sender
{
	
	
	if(!self.isTheViewActive)
	{
		NSLog(@"move up, store svos:%f",self.svos.y);
		self.isTheViewActive = YES;
	}
	UITableViewCell * activeTableCell = (UITableViewCell *)sender;
    CGPoint tableCellOrigin = [[activeTableCell superview] convertPoint:activeTableCell.frame.origin toView:self.view ];
    CGFloat scrollPoint = self.view.frame.size.height/2  - activeTableCell.frame.size.height -44;
	NSLog(@"move up :%f,%f,%f",tableCellOrigin.y,scrollPoint,activeTableCell.frame.origin.y);
    if (tableCellOrigin.y > scrollPoint) {
        CGFloat scrollDistance = tableCellOrigin.y - scrollPoint;
		NSLog(@"move up, set content offset bb:%f",tableView.contentOffset.y);
        [self.tableView setContentOffset:CGPointMake(0.0f,scrollDistance) animated:YES];
		NSLog(@"move up, set content offset:%f",tableView.contentOffset.y);
    }
	
}

- (void) dismissTheView
{
	if (self.isTheViewActive)
	{
		NSLog(@"dismiss the view");
		[self moveDown:nil];
		CGRect screenRect = [[UIScreen mainScreen] applicationFrame];
		CGRect endFrame = self.theView.frame;
		endFrame.origin.y = screenRect.origin.y + screenRect.size.height;
		
		[UIView animateWithDuration:0.3
						 animations:^{
							 theView.frame = endFrame;
							 //self.view.frame = newFrame;
						 }
						 completion:^(BOOL finished){ [theView removeFromSuperview]; }];
        
	}
}

#pragma mark -
#pragma mark UITextFieldDelegate

- (void)touchesEnded
{
	NSLog(@"touches ended");
	//if (self.isTheViewActive) {
    //		[self dismissTheView];
    //	}
	
	[keywordTextField resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	// the user pressed the "Done" button, so dismiss the keyboard
	[textField resignFirstResponder];
	return YES;
}

- (void) textFieldActive:(id)sender
{
	// remove the "Done" button in the nav bar????????
	//self.navigationItem.rightBarButtonItem = nil;
	
	[self dismissTheView];
}

- (NSString *) getStringFromDate:(NSDate *) date
{
	NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
	[dateFormatter setDateFormat:DATE_FORMAT_STRING];
    NSString *strDate = [dateFormatter stringFromDate:date];
	[dateFormatter release];
	
	return strDate;
	
}

#pragma mark -
#pragma mark Network Activities

- (void) sendRequest {
	NSLog(@"SENDING REQUEST");
    
	NSString *strURL = (NSString*)[JMUtilities getSetting:@"serviceBaseURL"];
    NSLog(@"Base URL:%@",strURL);
	NSString *newString = [(NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)strURL, NULL, CFSTR(" "), kCFStringEncodingUTF8) autorelease];
	if (newString) {
		
        
		NSURL * URL = [NSURL URLWithString:newString];
		
		ASIHTTPRequest * searchRequest = [ASIHTTPRequest requestWithURL:URL];	
		searchRequest.tag = -1;
		[searchRequest setDelegate:self];
		[searchRequest setTimeOutSeconds:TIMEOUTSECONDES];
        
		[self.loadingView removeFromSuperview];
		self.loadingView = [JMLoadingView loadingViewInView:self.view WithText:NSLocalizedString(@"Loading Leon List...",nil)];	
		[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
        
        
        [NSThread detachNewThreadSelector:@selector(synchronousRequest:) toTarget:self withObject:searchRequest];
        
		
        
		
	}	
}

- (void) synchronousRequest:(ASIHTTPRequest *)searchRequest {
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    [searchRequest start];
    if (searchRequest.responseStatusCode == 200)
        [self syncRequestFinished:searchRequest];
    else
        [self syncRequestFailed:searchRequest];
    [pool release];
	pool = nil;
}

- (void)syncRequestFailed:(ASIHTTPRequest *)request {
    [self.loadingView removeView];
    self.loadingView = nil;
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;	
	NSString *response = [request responseString];
	
	NSError * error = [request error];
	
	NSLog(@"failed:%@, %@, %d, with response: %@, reason:%@",self.title, request.url,request.tag,response,[error description]);
	
    
	UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"NetworkError",nil) 
														message:NSLocalizedString(@"NetworkErrorMessage",nil) 
                                                       delegate:self
                                              cancelButtonTitle:NSLocalizedString(@"Cancel",nil) 
                                              otherButtonTitles:NSLocalizedString(@"Try Again",nil),nil ];
    
	[alertView show];
	[alertView release];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { 
	switch(buttonIndex) {
		case 0:
			//cancel
            NSLog(@"cancel alerview");
			break;
		case 1:
			//ok
		{
            NSLog(@"try again to send request");
			[self sendRequest];
			
		}	
			
			break;
		default:
			break;
	}
}

- (void)syncRequestFinished:(ASIHTTPRequest *)request{
	//if (self.loadingView) {
    [self.loadingView removeView];
    self.loadingView = nil;
	//}
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;	
	NSData *responseData = [request responseData];
	NSString *responseString = [[[NSString alloc] initWithData:responseData 
													  encoding:NSUTF8StringEncoding] autorelease];
	

	NSLog(@"request finished, start json parsing:%@",responseString);
    //NSLog(@"%@",responseString);
	NSError *error;
	SBJSON *json = [[SBJSON new] autorelease];
	id jsonObject = [json objectWithString:responseString error:&error] ;
    if([jsonObject isKindOfClass:[NSArray class]]) {
        NSLog(@"SUCCESSFULLY PARSED THE JSON");
        self.words = [NSMutableArray arrayWithArray:[jsonObject copy]];
		for (int i=0; i<[(NSArray *)jsonObject count]; i++) {
            NSDictionary *item = (NSDictionary *)[(NSArray*)jsonObject objectAtIndex:i];
            NSString *name = (NSString *)[item objectForKey:@"Name"];
            NSLog(@"Name:%@",name);
            
//            //run sample collection in another thread
//            if ( finished) //!started || finished 
//            {
//                NSLog(@"not active.");
//                [self.programs removeObject:item];
//            }
        } 
	}
    else
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"ServiceError",nil) 
                                                            message:NSLocalizedString(@"ServiceErrorMessage",nil) 
                                                           delegate:self
                                                  cancelButtonTitle:NSLocalizedString(@"Cancel",nil) 
                                                  otherButtonTitles:NSLocalizedString(@"Try Again",nil),nil ];
        alertView.tag = 2000;
        [alertView show];
        [alertView release];
    }
    NSLog(@"after json parsing");
	[self.tableView reloadData];	
	
	
}

@end
